import React from 'react';
import { DatePicker, Select, Button } from 'antd';
import { useDebounceFn } from 'ahooks';
import { connect } from 'umi';

import { TRMessage } from '#/components';
import { UploadOutlined } from '#/utils/antdIcons';
import { TradeType } from '@/pages/ETrade/MediumAndLongTermMarket/constant';
import { export_json_to_excel } from '@/utils/fileExport';
import { useTRState } from '@/pages/ETrade/components';
import ImportBtn from '../ImportBtn';

import styles from './index.less';

const { Option } = Select;
const { RangePicker } = DatePicker;

export const Operate = (props) => {
  const exportKey = 'MediumAndLongTermMarket';
  const [first, setFirst] = React.useState(true);
  const [marketId, setMarketId] = React.useState(props.marketId);
  const [state, setState] = useTRState({
    canImport: props.buttonPermissions.some((item) => item.menuCode === exportKey),
  });

  // 初始化页面数据
  React.useEffect(() => {
    props.handlePageLoadEffect();
    setFirst(true);
  }, []);

  // 默认查询页面
  React.useEffect(() => {
    if (!props.selectedSequenceId) return;
    if (first) {
      query();
    }
    setFirst(false);
  }, [props.selectedSequenceId]);

  const formChange = useDebounceFn(
    () => {
      props.fetchSequenceListEffect();
    },
    { wait: 500 },
  ).run;

  // 当选择的省份||日期||交易类型发生改变时，重新获取交易序列列表
  React.useEffect(() => {
    if (props.provinceIdHistory && props.targetDate && props.selectedTradeType) {
      formChange();
    }
  }, [props.provinceIdHistory, props.targetDate, props.selectedTradeType]);

  // 查询
  const query = () => {
    if (!props.selectedSequenceId) {
      return TRMessage.warning('请先选择交易序列');
    }
    props.setDataTradeType(props.selectedTradeType);
    if (props.selectedTradeType === TradeType.CENTRALIZED.value) {
      props.fetchCentralizedBiddingInfosEffect();
    } else {
      props.fetchRollingBatchInfosEffect();
    }
  };

  // 导出
  const exportExcel = () => {
    if (
      !props.buttonPermissions.filter((item) => item.menuCode === 'MediumAndLongTermMarketExport')
        .length
    ) {
      return TRMessage.info('请联系管理员获取相关权限');
    }

    let params = {
      header: null,
      data: null,
      filename: null,
    };

    if (props.dataTradeType === TradeType.CENTRALIZED.value) {
      params.header = [
        '时点',
        '成交电量(日均)',
        '买方申报电量(日均)',
        '卖方申报电量(日均)',
        '边际买方申报电量(日均)',
        '边际卖方申报电量(日均)',
        '边际价格',
        '边际买方申报电价',
        '边际卖方申报电价',
      ];
      let data = [];
      props.centralizedTableData.forEach((item) => {
        let dataItem = [
          item.timeOrder,
          item.averageClearingPower.toFixed(3),
          item.purchaserPower.toFixed(3),
          item.sellerPower.toFixed(3),
          item.purchaserMarginalPower.toFixed(3),
          item.sellerMarginalPower.toFixed(3),
          item.marginalPrice.toFixed(2),
          item.purchaserMarginalPrice.toFixed(2),
          item.sellerMarginalPrice.toFixed(2),
        ];
        data.push(dataItem);
      });
      params.data = data;
      params.filename = '集中竞价序列出清量价信息';
    } else {
      params.header = [
        '时点',
        '算数平均价',
        '中位数价格',
        '最低价格',
        '最高价格',
        '上限价格',
        '下限价格',
        '日前电价',
        '成交电量(日均)',
      ];
      let data = [];
      props.rollingTableData.forEach((item) => {
        let dataItem = [
          item.timeOrder,
          item.weightedAveragePrice.toFixed(2),
          item.midPrice.toFixed(2),
          item.lowestPrice.toFixed(2),
          item.highestPrice.toFixed(2),
          item.floorPrice.toFixed(2),
          item.ceilPrice.toFixed(2),
          item.proposedPrice.toFixed(2),
          item.clearPower.toFixed(3),
        ];
        data.push(dataItem);
      });
      params.data = data;
      params.filename = '滚动撮合序列出清量价信息';
    }
    export_json_to_excel(params);
  };
  //默认请求
  const defaultRequest = () => {
    setMarketId(props.marketId);
    props.handlePageLoadEffect();
    props.setSelectedTradeType(TradeType.CENTRALIZED.value);
    setFirst(true);
    props.setProvinceIdHistory(props.marketList[0].provinceId);
    props.setMarketIdHistory(props.marketList[0].marketId);
  };
  const _onReset = useDebounceFn(
    () => {
      defaultRequest();
    },
    { wait: 500 },
  );

  const { canImport } = state;
  return (
    <div className={styles.Operate}>
      <div className={styles.condition}>
        <Select
          s
          showSearch
          filterOption={(input, option) => {
            return (option?.label).toLowerCase().includes(input.toLowerCase());
          }}
          className={styles.provinceSelect}
          value={props.marketIdHistory}
          onChange={(e, { provinceId }) => {
            props.setMarketIdHistory(e);
            props.setProvinceIdHistory(provinceId);
          }}
          options={props.marketList}
        />
        <RangePicker
          className={styles.dataPicker}
          allowClear={false}
          value={props.targetDate}
          format="YYYYMMDD"
          onChange={props.setTargetDate}
          separator="-"
        />
        <Select
          className={styles.tradeTypeSelect}
          value={props.selectedTradeType}
          onChange={props.setSelectedTradeType}
        >
          {(function () {
            let options = [];
            for (let key in TradeType) {
              options.push(
                <Option value={TradeType[key].value} key={TradeType[key].value}>
                  {TradeType[key].label}
                </Option>,
              );
            }
            return options;
          })()}
        </Select>
        <Select
          className={styles.seqSelect}
          value={props.selectedSequenceId}
          onChange={props.setSelectedSequenceId}
          showSearch={true}
          filterOption={(input, option) =>
            option.children.toLowerCase().includes(input.toLowerCase())
          }
        >
          {(function () {
            let options = [];
            for (let key in props.sequences) {
              options.push(
                <Option value={props.sequences[key].id} key={props.sequences[key].id}>
                  {props.sequences[key].sequenceTitle}
                </Option>,
              );
            }
            return options;
          })()}
        </Select>
        <Button className={styles.queryBtn} type="primary" onClick={query}>
          查询
        </Button>
        <Button className={styles.reset} htmlType="reset" onClick={_onReset.run} ghost>
          重置
        </Button>
      </div>
      {(props.dataTradeType === TradeType.CENTRALIZED.value && props.centralizedTableData.length) ||
      (props.dataTradeType === TradeType.ROLLING.value && props.rollingTableData.length) ? (
        <div className={styles.exportBtnGroup}>
          <ImportBtn disabled={!canImport} formChange={() => formChange()} />
          <Button
            style={{ padding: '0 0 0 10px' }}
            type="link"
            icon={<UploadOutlined />}
            onClick={exportExcel}
          >
            导出
          </Button>
        </div>
      ) : (
        <div>
          <ImportBtn disabled={!canImport} />
        </div>
      )}
    </div>
  );
};

const mapStateToProps = ({ mediumAndLongTermMarket, global }) => ({
  buttonPermissions: global.configure.buttonPermissions,
  provinceList: mediumAndLongTermMarket.provinceList,
  provinceIdHistory: mediumAndLongTermMarket.provinceIdHistory,
  targetDate: mediumAndLongTermMarket.targetDate,
  selectedTradeType: mediumAndLongTermMarket.selectedTradeType,
  sequences: mediumAndLongTermMarket.sequences,
  selectedSequenceId: mediumAndLongTermMarket.selectedSequenceId,
  dataTradeType: mediumAndLongTermMarket.dataTradeType,
  centralizedTableData: mediumAndLongTermMarket.centralizedTableData,
  rollingTableData: mediumAndLongTermMarket.rollingTableData,
  marketList: mediumAndLongTermMarket.marketList,
  marketId: mediumAndLongTermMarket.marketId,
  marketIdHistory: mediumAndLongTermMarket.marketIdHistory,
  marketIdMarket: mediumAndLongTermMarket.marketIdMarket,
});

const mapDispatchToProps = (dispatch) => ({
  setProvinceId: (payload) =>
    dispatch({
      type: 'mediumAndLongTermMarket/setProvinceId',
      payload,
    }),
  fetchSequenceListEffect: () =>
    dispatch({
      type: 'mediumAndLongTermMarket/fetchSequenceListEffect',
    }),
  fetchCentralizedBiddingInfosEffect: () =>
    dispatch({
      type: 'mediumAndLongTermMarket/fetchCentralizedBiddingInfosEffect',
    }),
  fetchRollingBatchInfosEffect: () =>
    dispatch({
      type: 'mediumAndLongTermMarket/fetchRollingBatchInfosEffect',
    }),
  setTargetDate: (payload) =>
    dispatch({
      type: 'mediumAndLongTermMarket/setTargetDate',
      payload,
    }),
  setSelectedTradeType: (payload) =>
    dispatch({
      type: 'mediumAndLongTermMarket/setSelectedTradeType',
      payload,
    }),
  setSelectedSequenceId: (payload) =>
    dispatch({
      type: 'mediumAndLongTermMarket/setSelectedSequenceId',
      payload,
    }),
  setDataTradeType: (payload) =>
    dispatch({
      type: 'mediumAndLongTermMarket/setDataTradeType',
      payload,
    }),
  handlePageLoadEffect: () =>
    dispatch({
      type: 'mediumAndLongTermMarket/handlePageLoadEffect',
    }),
  setProvinceIdHistory: (payload) =>
    dispatch({
      type: 'mediumAndLongTermMarket/setProvinceIdHistory',
      payload,
    }),
  setMarketIdHistory: (payload) =>
    dispatch({
      type: 'mediumAndLongTermMarket/setMarketIdHistory',
      payload,
    }),
});

export default connect(mapStateToProps, mapDispatchToProps)(Operate);
